<template>
  <div class="statistics-container">
    <div class="flex items-center back-btn">
      <el-icon><ArrowLeft /></el-icon>
      <el-button link @click="handleBack">返回上一页</el-button>
    </div>
    <ContentWrap>
      <section>
        <div class="flex items-center">
          <span>基本信息</span>
          <span class="ml-2" style="color: #c00">{{agentAreaName}}</span>
        </div>
        <div class="p-4">
          <el-row>
            <el-col :span="8">
              <div>代理商姓名：{{ agentInfo.agentName }}</div>
            </el-col>
            <el-col :span="8">
              <div>手机号码：{{ agentInfo.mobile }}</div>
            </el-col>
            <el-col :span="8">
              <div>所在地区订单总数：{{ agentInfo.orderCount || 0 }} 个</div>
            </el-col>
          </el-row>
          <el-row class="mt-4">
            <el-col :span="8">
              <div>注册时间：{{ formatDate(agentInfo.registerTime) }}</div>
            </el-col>
            <el-col :span="8">
              <div>直属门店数量：{{ agentInfo.directStoreCount || 0 }} 家</div>
            </el-col>
            <el-col :span="8">
              <div>所在地区注册人数：{{ agentInfo.registerUserCount || 0 }} 个</div>
            </el-col>
          </el-row>
          <el-row class="mt-4">
            <el-col :span="8">
              <div>佣金总额：￥{{ floatToFixed2(agentInfo.commissionTotal) || 0 }} </div>
            </el-col>
            <el-col :span="8">
              <div>区域门店数量：{{ agentInfo.areaStoreCount || 0 }} 家</div>
            </el-col>
            <el-col :span="8">
              <div>地区订单金额：￥{{ floatToFixed2(agentInfo.orderAmount) || 0 }} </div>
            </el-col>
          </el-row>
          <el-row class="mt-4">
            <el-col :span="8">
              <div>提现总额：￥{{ floatToFixed2(agentInfo.withdrawTotal) || 0 }} </div>
            </el-col>
            <el-col :span="8">
              <div>区域代理商数量：{{ agentInfo.areaAgentCount || 0 }} 个</div>
            </el-col>
            <el-col :span="8">
              <div>地区成功订单总额：￥{{ floatToFixed2(agentInfo.successfulOrderAmount) || 0 }} </div>
            </el-col>
          </el-row>
        </div>
      </section>
    </ContentWrap>
    <ContentWrap>
      <h3 class="mb-4">提现记录</h3>
      <el-table :data="recordList" style="width: 100%" border>
        <el-table-column label="提现时间" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="提现金额" align="center">
          <template #default="scope"> ￥{{ floatToFixed2(scope.row.price) }} </template>
        </el-table-column>
        <el-table-column label="提现状态" align="center">
          <template #default="scope">
            {{ commissionStatusMap[scope.row.status] || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.transferTime) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" >
          <template #default="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <el-card class="mb-4">
      <template #header>
        <CardTitle title="业绩统计" />
      </template>
      <div class="flex items-center gap-4">
        <span>查询时间</span>
        <el-radio-group v-model="dateType" @change="handleDateTypeChange">
          <el-radio-button label="全部" value="" />
          <el-radio-button label="今天" value="today" />
          <el-radio-button label="昨天" value="yesterday" />
          <el-radio-button label="本周" value="week" />
          <el-radio-button label="上周" value="lastWeek" />
          <el-radio-button label="本月" value="month" />
          <el-radio-button label="上月" value="lastMonth" />
          <el-radio-button label="本季度" value="quarter" />
          <el-radio-button label="上季度" value="lastQuarter" />
          <el-radio-button label="今年" value="year" />
          <el-radio-button label="去年" value="lastYear" />
        </el-radio-group>
        <el-date-picker
          v-model="dateTime"
          type="daterange"
          unlink-panels
          style="max-width: 300px"
          range-separator="至"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateRangeChange"
        />
        <el-button type="primary" class="ml-4" @click="handleSearch">
          <el-icon><Search /></el-icon>
          查询
        </el-button>
      </div>
      <div class="mt-4">
        <el-radio-group v-model="storeStatus" @change="storeStatusChange"> " >
          <el-radio-button label="全部" value="" />
          <el-radio-button label="门店进货订单" value="2" />
          <el-radio-button label="电商订单" value="1" />
        </el-radio-group>
      </div>
    </el-card>
    <ContentWrap>
      <el-table 
        :data="tableData" 
        v-loading="orderloading" 
        style="width: 100%" 
        border
        :key="orderqueryParams.pageNo + '-' + orderqueryParams.pageSize"
      >
        <StoreTablecolumn :list="tableData">
          <template #default="{ row }">
            <div>
              <el-button type="primary" v-if="row.shareBenefitType === 'shop_order_payment' "  @click="openDetail(row)"> 查看详情 </el-button>
            </div>
          </template>
        </StoreTablecolumn>
      </el-table>
      <Pagination
        :total="totalOrderCount"
        v-model:page="orderqueryParams.pageNo"
        v-model:limit="orderqueryParams.pageSize"
        @pagination="handleSearch"
      />
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import { ArrowLeft, Search } from '@element-plus/icons-vue'
import { CardTitle } from '@/components/Card'
import { StoreTablecolumn } from './data'
import {
  formatDate,
  defaultShortcuts,
  getDateRangeByText,
  getDateRangeStringByText
} from '@/utils/formatTime'
import { floatToFixed2 } from '@/utils'
import {
  getAgentUsersDetail,
  getAgentUsersWithdrawPage,
  getAgentOrderPage
} from '@/api/mall/agent/index'
import { store } from '@/store'

// 定义组件名，便于keep-alive识别
defineOptions({ name: 'AgentStatistics' })

const { currentRoute, push } = useRouter()

// 声明组件事件
const emits = defineEmits<{
  (e: 'agentBack'): void
}>()

const props = defineProps({
  info: {
    type: Object,
    default: () => ({})
  }
})

const handleBack = () => {
  emits('agentBack')
}
const commissionStatusMap = {
  0: '审核中',
  10: '审核通过',
  11: '提现成功',
  20: '审核不通过',
  21: '提现失败'
}
const stateInfo = reactive({
  tableData: [],
  dateType: '',
  storeStatus: '',
  dateTime: [] as string[],
  recordList: [] as any[],
  queryParams: {
    pageNo: 1,
    pageSize: 10,
  },
  agentInfo: {} as any,
  orderloading: false
})
const totalOrderCount = ref(0)
const orderqueryParams = ref<any>({
  pageNo: 1,
  pageSize: 10,
  createTime: [] as any[],
  selectShareBenefitType: ''
})
const {
  tableData,
  dateType,
  dateTime,
  queryParams,
  agentInfo,
  recordList,
  storeStatus,
  orderloading
} = toRefs(stateInfo)

const agentAreaName = computed(() => {
  const areaTYpe = props.info?.areaType || (props.info?.level === 2 ? '省代理' : props.info?.level === 3 ? '市代理' : '区代理')
  const areaName = props.info?.areaLevels?.[0]?.fullName || props.info?.name || ''
  return areaTYpe +'-'+ areaName
})
const storeStatusChange = () => {
  orderqueryParams.value.pageNo = 1
  handleSearch()
}
// 处理日期类型变化
const handleDateTypeChange = (value: string) => {
  if (!value) {
    stateInfo.dateTime = []
    return
  }
  
  // 使用工具函数获取日期范围
  const [startDate, endDate] = getDateRangeByText(value)
  
  if (startDate && endDate) {
    stateInfo.dateTime = [
      formatDate(startDate, 'YYYY-MM-DD HH:mm:ss'),
      formatDate(endDate, 'YYYY-MM-DD HH:mm:ss')
    ]
  }
}

// 处理日期范围变化
const handleDateRangeChange = (value: any) => {
  if (value) {
    stateInfo.dateType = ''
  }
}

const handleSearch = async () => {
  let startDate: Date | null = null
  let endDate: Date | null = null

  // 根据选择的文案转换时间范围
  if (dateType.value) {
    const [start, end] = getDateRangeByText(dateType.value)
    startDate = start
    endDate = end
  } else if (dateTime.value && dateTime.value.length === 2) {
    // 如果选择了自定义日期范围
    startDate = new Date(dateTime.value[0])
    endDate = new Date(dateTime.value[1])
  }
  
  // 这里可以调用API进行查询
  orderqueryParams.value = {
    ...orderqueryParams.value,
    createTime: startDate && endDate ? [
      formatDate(startDate, 'YYYY-MM-DD HH:mm:ss'),
      formatDate(endDate, 'YYYY-MM-DD HH:mm:ss')
    ] : [],
    selectShareBenefitType: storeStatus.value ? Number(storeStatus.value) : undefined
  }
  
  // 重置表格数据，确保在获取新数据前清空旧数据
  // tableData.value = []
  
  // 获取新的订单数据
  await getOrderInfo()
}
const openDetail = (row: any) => {
  push({ name: 'TradeOrderDetail', params: { id:row.orderId } })
}
const getUsersDetail = async () => {
  const agentId = props.info?.areaType? props.info.id : props.info.agentId
  const res = await getAgentUsersDetail({ id:agentId })
  const res2 = await getAgentUsersWithdrawPage({ ...queryParams.value, agentId: agentId })
  // const res3 = await getAgentOrderPage({ ...orderqueryParams.value })
  // console.log('2025年06月18日09:32:31:00:00', defaultShortcuts)
  agentInfo.value = res
  recordList.value = res2.list
}
const getOrderInfo = async () => {
  orderloading.value = true
  try {
    const res = await getAgentOrderPage({ ...orderqueryParams.value, agentId: props.info?.areaType? props.info.id : props.info.agentId })
    tableData.value = res.list
    totalOrderCount.value = res.total
  } finally {
    orderloading.value = false
  }
}
onMounted(() => {
  getUsersDetail()
  
  // 设置默认日期类型为"全部"
  stateInfo.dateType = ''
  stateInfo.dateTime = []
  
  handleSearch()
})
</script>

<style scoped lang="scss">
.statistics-container {
  height: 100%;
  .back-btn {
    margin-bottom: 20px;
  }
  section {
    font-size: 14px;
    padding: 20px;
  }
}
</style>
